"use strict";
(function(win) {
  var debounceTimer = null // 防抖动计时器
  var throttleTimer = null // 节流计时器

/**
 * 节流函数:
 *      节流：控制流量，单位时间内事件只能触发一次，如果服务器端的限流即 Rate Limit。
 *      代码实现重在开锁关锁 timer=timeout; timer=null
 */
function throttle(f, wait = 100) {
  if (throttleTimer) {
      return
  }
  throttleTimer = setTimeout(() => {
      f()
      throttleTimer = null // 节流重在开关锁
  }, wait)
}

  /**
   * 防抖函数:
   *      防止抖动，单位时间内事件触发会被重置，避免事件被误伤触发多次。
   *      代码实现重在清零 clearTimeout
   */
  function debounce(f, wait = 100) {
    clearTimeout(debounceTimer) // 防抖重在清零
    debounceTimer = setTimeout(f, wait)
  }

  // 设置cookie
  function setCookie (key,value, exhours) {
    var exp = new Date()
    exp.setTime(exp.getTime() + exhours * 60 * 60 * 1000)
    document.cookie = key + "="+ escape (value) + ";expires=" + exp.toGMTString()
  }

  // 获取token
  function getCookie (name) {
      var reg = new RegExp("(^| )"+name+"=([^;]*)(;|$)")
      var arr = document.cookie.match(reg)
      if(arr) {
        return unescape(arr[2])
      } else {
        return null
      }
  }

  // 删除cookie
  function delCookie (name) {
    var exp = new Date()
    var cval = getCookie(name)
    exp.setTime(exp.getTime() - 1)
    if(cval) {
      document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
  }

  var ssaSdk = {
    // 存储信息
    loginOut() {
      delCookie('token')
      delCookie('userId')
      delCookie('userName')
    },
    loginIn(res) {
      setCookie('token', res.token)
      setCookie('userId', res.userId)
      setCookie('userName', encodeURIComponent(res.userName))
    },
    // 获取token
    getToken() {
      const token = getCookie('token')
      if(!token) {
        throttle(function () {
          window.location.hash = '#/login'
        })
      }
      return token
    },
    // 获取token
    getUserInfo() {
      return {
        userId: getCookie('userId'),
        userName: decodeURIComponent(getCookie('userName'))
      }
    }
  }

  win.ssaSdk = ssaSdk
})(window)